package com.chen.framework.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.framework.model.sys.SysDict;
import com.chen.framework.model.sys.SysDictData;
import com.chen.base.module.mybatis.utils.WrapperUtil;
import com.chen.base.utils.StreamUtil;
import com.chen.framework.mapper.SysDictDataMapper;
import com.chen.framework.mapper.SysDictMapper;
import com.chen.framework.service.inter.SysDictService;
import com.chen.framework.vo.DictVO;
import com.chen.root.base.PageData;
import com.chen.root.base.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author ChenJinLong
 * @since 2023-09-22
 */
@Slf4j
@Service
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements SysDictService {

    @Resource
    private SysDictDataMapper sysDictDataMapper;

    @Override
    public R<PageData<DictVO>> dictPage(SysDict sysDict, Integer currPage, Integer pageSize) {
        // 分页查询数据字典概述
        Page<SysDict> page = page(new Page<>(currPage, pageSize), WrapperUtil.queryWrapperByEntity(sysDict));
        List<DictVO> voList = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(page.getRecords())){
            // 查询数据字典详细信息
            List<Long> dictIds = StreamUtil.map(page.getRecords(), SysDict::getDictId);
            LambdaQueryWrapper<SysDictData> dataWrapper = Wrappers.lambdaQuery(SysDictData.class);
            dataWrapper.eq(StrUtil.isNotBlank(sysDict.getStatus()), SysDictData::getStatus, sysDict.getStatus());

            List<SysDictData> sysDictDataList = sysDictDataMapper.selectList(
                    dataWrapper.in(SysDictData::getDictId,dictIds)
            );

            // 构建返回数据实体
            Map<Long, List<SysDictData>> dictDataMap = StreamUtil.groupBy(sysDictDataList, SysDictData::getDictId);
            page.getRecords().forEach(di -> voList.add(new DictVO(di, dictDataMap.get(di.getDictId()))));
        }

        return R.ok(PageData.build(currPage, pageSize, page.getTotal(), voList));
    }
}
